'use strict';

const jwt = require('jsonwebtoken');

module.exports = (options, app) => {

  function pathCanonizeize(path) {
    ['?', '#'].forEach(stopWord => {
      const index = path.indexOf(stopWord);
      if (index !== -1) { path = path.substring(0, index); }
    });

    return path;
  }


  function authenticate(context) {
    console.log(context.response);
    const header = context.request.header;
    const accessToken = header.hasOwnProperty('access_token') ? header.access_token : '';
    if (/^(|^\s+)$/.test(accessToken)) {
      context.response.fail('Access is denied, you must first login', 401, 'Unauthorized');
      return false;
    }

    const tokenService = new context.app.serviceClasses.token(context);
    const currentUser = tokenService.verifyToken(accessToken);
    if (!currentUser.isSuccess) {
      context.response.fail('Token is not legal', 401, 'Unauthorized');
      return false;
    }

    return true;
  }


  function isMatched(context, rules) {
    const request = context.request;
    return rules.some(item => {
      if (item instanceof RegExp) {
        console.log(item.test(pathCanonizeize(request.url)));
        return item.test(pathCanonizeize(request.url));
      }
      return item === pathCanonizeize(request.url);

    });
  }


  return function* auth(next) {
    if (options.exclude && options.exclude.length) {
      if (isMatched(this, options.exclude)) {
        return yield next;
      }
    }

    if (authenticate(this, this.request)) {
      yield next;
    }
  };
};
